#pragma once

#include <iostream>
#include <sys/types.h>          
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>
#include <pthread.h>

#include "log.hpp"

extern Log log;

enum {
    SOCKET_ERR = 1,
    BIND_ERR = 2
};

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

//using namespace用于引入命名空间
//using 还可以用于类型别名定义
//using uint = unsigned int
using func_t = std::function<std::string(const std::string&,const std::string&,uint16_t)>;
//typedef std::function<std::string(const std::string&)> func_t;

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport,const std::string &ip = defaultip)
        :port_(port),ip_(ip),isruning_(false),sockfd_(0)
    {}

    void Init()
    {
        //1. 创建udp socket
        //2. Udp 的socket是全双工的, 允许被同时读写的
        sockfd_ = socket(AF_INET,SOCK_DGRAM,0);
        if (sockfd_  < 0)
        {
            log(Fatal,"scoket create error, sockfd: %d",sockfd_);
            exit(SOCKET_ERR);
        }

        log(Info,"scoket create sucess, sockfd: %d",sockfd_);

        //2. bind socket
       // struct scokaddr_in local;
        struct sockaddr_in local;
        bzero(&local,sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(port_); //需要保证我们的端口号是网络字节序列, 因为该端口号是要发给对方的
        local.sin_addr.s_addr = inet_addr(ip_.c_str());   //1. string -> uint32_t 2. uint32_t必须是网络序列的

        //local.sin_addr.s_addr = INADDR_ANY;
        
        if (bind(sockfd_,(const sockaddr *)&local,sizeof(local)) < 0)
        {
            log(Fatal,"socket bind error, error: %d, err string: %s",sockfd_,errno,strerror(errno));
            exit(BIND_ERR);
        }

        log(Info,"bind sucess, error: %d, err string: %s",errno,strerror(errno));
    }

    // void Init()
    // {
    //     // 1. 创建udp socket
    //     sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); // PF_INET
    //     if(sockfd_ < 0)
    //     {
    //         log(Fatal, "socket create error, sockfd: %d", sockfd_);
    //         exit(SOCKET_ERR);
    //     }
    //     log(Info, "socket create success, sockfd: %d", sockfd_);
    //     // 2. bind socket
    //     struct sockaddr_in local;
    //     bzero(&local, sizeof(local));
    //     local.sin_family = AF_INET;
    //     local.sin_port = htons(port_); //需要保证我的端口号是网络字节序列，因为该端口号是要给对方发送的
    //     local.sin_addr.s_addr = inet_addr(ip_.c_str()); //1. string -> uint32_t 2. uint32_t必须是网络序列的 // ??
    //     // local.sin_addr.s_addr = htonl(INADDR_ANY);

    //     if(bind(sockfd_, (const struct sockaddr *)&local, sizeof(local)) < 0)
    //     {
    //         log(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
    //         exit(BIND_ERR);
    //     }
    //     log(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    // }

    void CheckUser(struct sockaddr_in& client,const std::string clientip,uint16_t clientport)
    {
        auto iter = oline_user_.find(clientip);
        if (iter == oline_user_.end())
        {
            oline_user_.insert({clientip,client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(const std::string &info,const std::string clientip, uint16_t clientport)
    {
        std::cout << "start BroadCast ..." << std::endl;
        
        for (const auto &user : oline_user_)
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";

            message += info;
            socklen_t len = sizeof(user.second);
            std::cout << message << std::endl;
            sendto(sockfd_,message.c_str(),sizeof(message),0,(struct sockaddr*)(&user.second),len);
        }
    }
 
    void Run()
    {
        isruning_ = true;
        char inbuffer[size]; 


        while (isruning_)
        {
            //std::cout << "isruning_ is true" << std::endl;
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_,inbuffer,sizeof(inbuffer) - 1,0,(sockaddr *)&client,&len);
            if (n < 0)
            {
                log(Warning,"recvfrom error,error: %d, err string: %s",errno,strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port); 
            std::string clientip = inet_ntoa(client.sin_addr);

            
            //log(Info,"recvfrom success, %s",strerror(errno));

            CheckUser(client,clientip,clientport);

            std::string info = inbuffer;
            Broadcast(info,clientip,clientport);

            // inbuffer[n] = 0;
            // std::string info = inbuffer;

            // //充当一次数据处理
            // std::string echo_string = func(info,clientip,clientport);
           
            // sendto(sockfd_,echo_string.c_str(),echo_string.size(),0,(const sockaddr *)&client,len);

            //log(Info,"sendto success, %s",strerror(errno));
        }
    }

    ~UdpServer()
    {
        if(sockfd_ > 0) close(sockfd_);
    }
private:
    int sockfd_; //网络文件描述符
    uint16_t port_; //表示服务器的端口号
    std::string ip_;
    std::unordered_map<std::string,struct sockaddr_in> oline_user_;
    bool isruning_;
};


